import router from './index';
import store from '../store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	const {
		path,
		meta: { title }
	} = to;
	// console.log(to, from);
	document.title = `${title} | ${store.getters.title}`;
	if (store.getters.token) {
		if (path === '/login') {
			next({ path: '/' });
			NProgress.done();
		} else {
			const info = store.getters.info;
			const routeTime = store.getters.routeTime;
			if (info.time === routeTime) {
				next();
			} else {
				try {
					// console.log('generateRoutes');
					await store.dispatch('routes/generateRoutes', info);
					// 解决刷新后路由定位到 AsyncRoutes 的问题
					if (to.redirectedFrom) {
						next(to.redirectedFrom);
					} else {
						next({ ...to, replace: true });
					}
				} catch (e) {
					await store.dispatch('account/RESET_STATE');
					next(`/login?redirect=${path}`);
					NProgress.done();
				}
			}
		}
	} else {
		if (whiteList.includes(path)) {
			// in the free login whitelist, go directly
			next();
		} else {
			// other pages that do not have role to access are redirected to the login page.
			next(`/login?redirect=${path}`);
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
